import { Injectable } from '@nestjs/common';
import { UserService } from "../user/user.service";
import { JwtService } from '@nestjs/jwt';
import {password} from '../../utils/_crypto';
import { User } from '../../entities/user.entities';

@Injectable()
export class AuthService {
  constructor(
    private readonly userService: UserService,
    private readonly jwtService: JwtService
  ) {}

  async validateUser(username: string, pass: string): Promise<any> {
    const user = await this.userService.findOneByName(username);
    if (user && user.password === password(pass)) {
      const { password, ...result } = user;
      return result;
    }
    return null;
  }

  async login(user: any) {
    const payload = { username: user.username, user_id: user.id, email_status: user.email_status };
    this.userService.userRepository.save(user);
    return {
      access_token: this.jwtService.sign(payload),
      expires_time: '2h'
    };
  }
  
  async activeMail(user_id: number){
    const user=await this.userService.findOneByID(user_id)
    const payload={userId: user_id,userEmail: user.email}
    const token=this.jwtService.sign(payload)
    return {
      token: token,
      expires_time: '2h',
      email: user.email
    };
  }

  verfiyMail(token: string):boolean|any{
    let info;
    try{
      info=this.jwtService.verify(token);
    }catch(err){
      return false
    }
    return info;
  }
}
